﻿var TermExamination = new function () {
    var self = this;
    var termElement, startExamBtn, examInfoElement;
    var mainContent;

    self.Init = function () {
        mainContent = $("#content");
        termElement = $("#TermId", mainContent);
        startExamBtn = $('#btnStartExam', mainContent);
        examInfoElement = $('#ExamInformation', mainContent);

        self.GetExamInformation(termElement.val());
        self.BindEvents();
    };

    self.BindEvents = function () {

        startExamBtn.unbind('click').bind('click', function () {
            var param = JSON.stringify({
                'termId': termElement.val(),
            });
            $.ajax({
                url: '/Member/GenerateExamToken',
                type: 'POST',
                data: param,
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    if (data.Result == 'OK') {
                        var token = data.Data;
                        window.open("/Member/Exam?termId=" + termElement.val() + "&token=" + token, "Exam", "toolbar=0,location=0,status=0,menubar=0,resizable=0,width=780,height=800");
                    }
                },
                error: function () {
                }
            });

        });

        termElement.change(function () {
            self.GetExamInformation(termElement.val());

        });
    };
    self.GetExamInformation = function (term) {
        if (term == undefined || term <= 0) return;

        var lsparams = JSON.stringify({
            'termId': term
        });
        $.ajax({
            url: '/Member/GetExamInformation',
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: lsparams,
            success: function (data) {
                if (data.Result == 'OK') {
                    //examInfoElement.html('This Examination Section have total ' + data.TotalRecord + ' question.');
                    var html = '<ol>';
                    for (var i = 0; i < data.Records.length; i++) {
                        html += "<li>" + data.Records[i].SectionName + ":<span class='exam-question'>" + data.Records[i].TotalQuestion + " Questions </span></li>";
                    }
                    html += "</ol>";
                    examInfoElement.html(html);
                    if (data.TotalRecord < 1) {
                        startExamBtn.addClass("ui-state-disabled").attr("disabled", true);
                    } else {
                        startExamBtn.removeClass("ui-state-disabled").attr("disabled", false);
                    }
                }
            },
            error: function () {
            }
        });
    };
};
var Examination = new function () {
    var self = this;
    var examination = null;
    var examCountdown;
    var mainContent;
    mainContent = $("#content");
    self.InitExam = function (termId) {
        var params = {
            'sectionId': 0,
            'termId': termId,
            'pageIndex': '0',
            'isNewExamination': true
        };
        mainContent.load("/Member/ExamDetails", params, function () {
            ExaminationDetails.Init();
            examination = {};
            examination[0] = 0;
        });
    };


    self.AddQuestionExam = function (key, value) {
        for (var keyExam in examination) {
            if (keyExam === key)
                self.RemoveQuestionExam(keyExam);
        }
        examination[key] = value;
    };

    self.RemoveQuestionExam = function (key) {
        delete examination[key];
    };

    self.UpdateQuestionExam = function (key, value) {
        self.RemoveQuestionExam(key);
        self.AddQuestionExam(key, value);
    };

    self.GetQuestionExam = function (key) {
        for (var keyExam in examination) {
            if (keyExam === key)
                return examination[key];
        }
        return null;
    };

    self.GetExamination = function () {
        return examination;
    };

    self.GetMainContent = function () {
        return mainContent;
    };

    self.SetExamCountdown = function (element) {
        examCountdown = element;
    };
};


var ExaminationDetails = new function () {
    var self = this;
    var mainContent;
    var resultModal;
    var examCountdown;
    var sectionId, questionNo, totalCount, questionId, answerId, termId;
    var examStart = false;
    self.Init = function () {
        mainContent = $("#content");
        resultModal = $("#resultModal");
        sectionId = $('#SectionId', mainContent).val();
        termId = $('#TermId', mainContent).val();
        questionNo = $('#QuestionNumber', mainContent).val() * 1;
        totalCount = $('#TotalQuestion', mainContent).val() * 1;
        questionId = $('#QuestionId', mainContent).val();
        answerId = null;
        self.BindStyles(questionNo + 1);
        self.BindEvents();
        self.CheckQuestion(questionId);
        self.ShowTimerCountdown();
        examStart = true;
    };
    self.CheckExamStart = function () {
        return examStart;
    };
    self.ShowTimerCountdown = function () {
        examCountdown = $('#ExamTimerCount');
        $.noty.defaults.layout = 'topRight';
        if (!examCountdown.length > 0) {
            var n = noty({
                text: 'Remaining Time :<div id="ExamTimerCount" class="countdown styled"></div>',
                template: '<div class="noty_message"><span class="noty_text"></span></div>',
                type: 'information',
                layout: 'topRight',
                timeout: false,
                force: true,
                killer: true,
                closeWith: ["button"]
            });

            $('#ExamTimerCount').countdown({
                date: +(new Date) + (totalCount * 60 * 1000),
                render: function (data) {
                    $(this.el).html("<div>" + this.leadingZeros(data.hours, 2) + " <span>hrs</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>min</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>sec</span></div>");
                },
                onEnd: function () {
                    $(this.el).html('Time is over. Your exam will be sumitted automaticallly!');
                    self.SubmitExamination();
                }
            });
        }
    };

    self.BindStyles = function (questionIndex) {
        if (questionIndex <= 1)
            $("#btnBack").addClass("ui-state-disabled").attr("disabled", true);
        if (questionIndex >= totalCount)
            $("#btnNext").addClass("ui-state-disabled").attr("disabled", true);
    };

    self.BindEvents = function () {
        $('#btnNext', mainContent).unbind('click').bind('click', function () {
            var questionIndex = questionNo + 1;
            self.ChangeQuestion(questionIndex);
        });

        $('#btnBack', mainContent).unbind('click').bind('click', function () {
            var questionIndex = questionNo - 1;
            self.ChangeQuestion(questionIndex);
        });

        $('#ListAnswer', mainContent).find("input[type=checkbox]").unbind('click').bind('click', function () {
            answerId = $(this).val();
            $('#ListAnswer', mainContent).find("input[type=checkbox]").parent().removeClass("checked");
            $(this).parent().addClass("checked");
            if (answerId) {
                Examination.AddQuestionExam(questionId, answerId);
            }
        });

        $('#btnSubmitExam', mainContent).unbind('click').bind('click', function () {
            self.ShowDialogConfirm();
        });
    };

    self.CheckQuestion = function (id) {
        var questionAnswer = Examination.GetQuestionExam(id);
        if (questionAnswer) {
            $('#answerCheckbox' + questionAnswer).parent().addClass("checked");
        }
    };

    self.ChangeQuestion = function (questionIndex) {
        var params = {
            'sectionId': 0,
            'termId': termId,
            'pageIndex': questionIndex,
            'isNewExamination': false
        };
        mainContent.load("/Member/ExamDetails", params, function () {
            ExaminationDetails.Init();
        });
    };

    self.ShowDialogConfirm = function () {
        $("#dialog-confirm").dialog({
            resizable: false,
            height: 130,
            modal: true,
            open: function () {
                var closeBtn = $('.ui-dialog-titlebar-close');
                closeBtn.hide();
            },
            buttons: {
                "Submit": function () {
                    $(this).dialog("close");
                    self.SubmitExamination();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
    };

    self.SubmitExamination = function () {
        var exam = Examination.GetExamination();
        var params = { 'examination': exam, 'sectionId': 0, 'termId': termId };
        $.noty.closeAll();
        resultModal.load("/Member/SubmitExamination", params, function () {
            resultModal.modal('show');
            resultModal.removeClass("hide").css("height", "300px");

            resultModal.on('hidden.bs.modal', function (e) {
                window.close();
            });
        });
    };
};

var ExaminationResult = new function () {
    var self = this;
    self.Init = function () {
        $("#progressbar").progressbar({
            value: 0
        });
        $("#progressbar > .ui-progressbar-value").animate({
            width: "37%"
        }, 500);
    };
};

var ExaminationHistory = new function () {
    this.SearchHistory = function (sortData) {
        var page = $("#exam-history-selectedpage").val();
        if ($("#exam-history-hidden-searchkeyword").val() != $('#exam-history-keyword').val()) {
            page = 0;
        }
        $('#exam-history-hidden-searchkeyword').val($('#exam-history-keyword').val());
        
        var requestData = {};
        requestData['pageIndex'] = page;
        requestData['keyword'] = $('#exam-history-keyword').val();
        // Build sorting data
        for (var sortKey in sortData) {
            requestData[sortKey] = sortData[sortKey];
        }
        
        $.ajax({
            url: "/Member/SearchExamHistory",
            cache: false,
            data: requestData,
            dataType: "html",
            success: function (data) {
                var datas = data.split('||||||||');
                $("#history-content").html(datas[0]);
                $("#history-paging").html(datas[1]);
            }
        });
    };
};

